<template>
    <view class="page-box">
        <template v-if="list.length > 0">
            <view class="bank-info-box" v-if="default_bank">
                <view class="name">{{default_bank.account_name}}</view>
                <view class="card-btn row bothSide verCenter">
                    <view class="card row">{{default_bank.id_card}}</view>
                    <view class="change-card row rowCenter verCenter" @click="changeCard">切换提现账号</view>
                </view>
                <view class="bank-name">{{default_bank.bank_name}}（{{default_bank.bank_number}}）</view>
            </view>
            <view class="withdraw-box">
                <view class="tit">提现金额</view>
                <view class="input-box row verCenter">
                    <text class="fuhao">￥</text>
                    <input type="number" class="uni-input" inputmode="decimal" placeholder="" placeholder-style="color:#999;" maxlength="10" v-model="withdraw_amount" />
                </view>
                <view class="msg-box row bothSide verCenter">
                    <view class="msg">当前余额 {{balance}}元</view>
                    <view class="btn" @click="allWithdrawals">全部提现</view>
                </view>
                <view class="submit row rowCenter verCenter" @click="addUserCashFlow">确认提现</view>
                <view class="tip">提现到账时间为工作日的14点与17点，请于当日17点前申请，过时将T+1到账。</view>
            </view>
        </template>
        <template v-else>
            <view class="no-data column rowCenter verCenter">
                <image src="@/static/card.dd09cd89.png" class="pic" mode="aspectFill"></image>
                <text class="tt">您还没有银行账号<br />请先去添加银行账号才能提现哦～</text>
            </view>
            <view class="add-btn row rowCenter verCenter" style="margin-top: 90rpx;" @click="accountAdd()">
                <text class="iconfont icon-jia"></text>
                <text class="tt">添加银行账号</text>
            </view>
        </template>
        <!-- 切换提现账号 -->
        <uni-popup ref="popup" background-color="#ffffff" border-radius="20rpx 20rpx 0 0">
            <view class="popup-content">
                <view class="title row rowCenter verCenter">请选择收款账号</view>
                <view class="list">
                    <view class="box row bothSide verCenter" v-for="(item,index) in list" :key="index">
                        <view class="text">
                            <view class="row verCenter">
                                <text class="t1">{{item.bank_name}}</text>
                                <text class="t2">{{item.account_name}}</text>
                            </view>
                            <view class="account">{{item.bank_number}}</view>
                        </view>
                        <view class="choice row rowCenter verCenter" @click="choice(index)">选择</view>
                    </view>
                </view>
            </view>
        </uni-popup>
        <!-- 新增收款账号 -->
        <uni-popup ref="popupAccountAdd" background-color="#ffffff" border-radius="20rpx 20rpx 0 0">
            <view class="popup-content">
                <view class="title row rowCenter verCenter">新增收款账号</view>
                <view class="input-box row bothSide verCenter">
                    <text class="label row">账号类型</text>
                    <view class="wrap row">
                        <text class="tt">银行卡</text>
                    </view>
                </view>
                <view class="input-box row bothSide verCenter">
                    <text class="label row">账户名</text>
                    <view class="wrap row">
                        <input type="text" placeholder="持卡人姓名（公司名）" class="uni-input" v-model="form.account_name" />
                    </view>
                </view>
                <view class="input-box row bothSide verCenter">
                    <text class="label row">身份证号</text>
                    <view class="wrap row">
                        <input type="text" placeholder="持卡人身份证号" class="uni-input" v-model="form.id_card" />
                    </view>
                </view>
                <view class="input-box row bothSide verCenter">
                    <text class="label row">卡号</text>
                    <view class="wrap row bothSide verCenter">
                        <input type="text" placeholder="银行卡号" class="uni-input" v-model="form.bank_number" />
                        <text class="iconfont icon-a-tubiaochangyongsousuo1" @click="identifyBankCard()"></text>
                    </view>
                </view>
                <view class="input-box row bothSide verCenter">
                    <text class="label row">所属银行</text>
                    <view class="wrap row bothSide verCenter">
                        <picker @change="bindPickerChange" :value="index" :range="arr">
                            <view class="picker-wrap row bothSide verCenter">
                                <input type="text" class="uni-input" placeholder="银行卡所属银行" v-model="arr[index]" />
                                <view class="iconfont icon-youjiantou"></view>
                            </view>
                        </picker>
                    </view>
                </view>
                <view class="input-box row bothSide verCenter">
                    <text class="label row">手机号</text>
                    <view class="wrap row">
                        <input type="number" inputmode="tel" placeholder="银行预留手机号" class="uni-input" v-model="form.tel" />
                    </view>
                </view>
                <view class="popup-btn row bothSide verCenter">
                    <view class="btn-ok row rowCenter verCenter" @click="addUserSettle">确认</view>
                </view>
            </view>
        </uni-popup>
    </view>
</template>

<script>
    import { API } from '@/util/api.js';

    export default {
        data() {
            return {
                withdraw_amount: '', //提现金额 
                balance: '',
                list: [],
                default_bank: [],
                index: -1,
                arr: ['中国工商银行', '中国农业银行', '中国建设银行', '中国银行', '中国邮政储蓄银行', '交通银行', '招商银行', '浦发银行', '中信银行', '华夏银行', '中国光大银行', '中国民生银行', '兴业银行', '广发银行', '平安银行', '浙商银行', '渤海银行', '恒丰银行', '中国交通银行'],
                form: {
                    account_name: '',
                    id_card: '',
                    bank_number: '',
                    bank_id: '',
                    tel: ''
                }
            };
        },
        onLoad(options) {
            this.balance = parseFloat(options.balance) || 0; //获取余额
        },
        onShow() {
            this.getUserSettle();
        },
        methods: {
            bindPickerChange(e) {
                this.index = e.detail.value;
                this.form.bank_id = this.index + 1;
            },
            /**
             * 切换提现账号
             */
            changeCard() {
                this.open();
            },
            /**
             * 获取用户银行列表
             */
            getUserSettle() {
                this.request(API.getUserSettle, 'GET', {}, true).then(res => {
                    if (res.code === 0) {
                        this.list = res.data.list.map(item => {
                            return {
                                ...item,
                                id_card: this.formatIdCard(item.id_card),
                                bank_number: this.formatBankNumber(item.bank_number)
                            };
                        });
                        this.default_bank = this.list[0];
                    } else {
                        uni.showToast({
                            title: res.msg,
                            icon: 'none'
                        });
                    }
                });
            },
            /**
             * 全部提现
             */
            allWithdrawals() {
                this.withdraw_amount = this.balance;
            },
            /**
             * 提现操作
             */
            addUserCashFlow() {
                if (this.withdraw_amount <= 0) {
                    uni.showToast({
                        title: '提现金额为零，不可提现',
                        icon: 'none'
                    });
                    return false;
                }
                if (this.withdraw_amount > this.balance) {
                    uni.showToast({
                        title: '提现金额不可大于余额',
                        icon: 'none'
                    });
                    return false;
                }

                this.request(API.addUserCashFlow, 'POST', { withdraw_amount: this.withdraw_amount, settle_account_id: this.default_bank.settle_account_id }, true).then(res => {
                    if (res.code === 0) {
                        uni.showToast({
                            title: '提现成功',
                            icon: 'success'
                        });
                        setTimeout(() => {
                            uni.switchTab({
                                url: '/pages/mine/index'
                            });
                        }, 2000)
                    } else {
                        uni.showToast({
                            title: res.msg,
                            icon: 'none'
                        });
                    }
                });
            },
            /**
             * 新增收款账号
             */
            accountAdd() {
                this.$refs.popupAccountAdd.open('bottom');
            },
            open() {
                this.$refs.popup.open('bottom');
            },
            close() {
                this.$refs.popup.close();
                this.$refs.popupAccountAdd.close();
            },
            /**
             * 识别银行卡
             */
            identifyBankCard() {
                uni.chooseImage({
                    count: 1,
                    sizeType: ['original', 'compressed'],
                    sourceType: ['album', 'camera'],
                    success: chooseImageRes => {
                        console.log('选择图片成功：', chooseImageRes);

                        // 显示loading
                        uni.showLoading({
                            title: '识别银行卡中...'
                        });

                        // 获取选择的图片路径数组
                        const tempFilePaths = chooseImageRes.tempFilePaths;

                        //上传到服务器
                        uni.uploadFile({
                            url: API.uploadImage,
                            filePath: tempFilePaths[0],
                            name: 'file',
                            formData: {
                                'source': 'appUser',
                                'is_use_ocr': 2 //是否使用图片识别，0-否，1-行驶证识别，2-银行卡识别，3-身份证识别
                            },
                            success: uploadFileRes => {
                                console.log('服务器上传图片成功：', uploadFileRes);
                                uni.hideLoading();
                                let data = JSON.parse(uploadFileRes.data);
                                if (data.code === 0) {
                                    this.form.bank_number = data.data.card_num;
                                    this.index = this.arr.indexOf(data.data.bank_name); //自动选中该银行
                                    this.form.bank_id = this.index + 1;
                                    this.$forceUpdate();
                                } else {
                                    uni.showToast({
                                        title: data.msg,
                                        icon: 'none'
                                    });
                                }
                            },
                            fail: () => {
                                uni.hideLoading();
                                uni.showToast({
                                    title: '上传图片失败',
                                    icon: 'none'
                                });
                            }
                        });
                    }
                });
            },
            /**
             * 选择银行卡
             */
            choice(index) {
                this.close();
                this.default_bank = this.list[index];
            },
            /**
             * 新增银行
             */
            addUserSettle() {
                if (!this.form.account_name) {
                    uni.showToast({
                        title: '持卡人姓名必填',
                        icon: 'none'
                    });
                    return false;
                }
                if (!this.form.id_card) {
                    uni.showToast({
                        title: '持卡人身份证号必填',
                        icon: 'none'
                    });
                    return false;
                }
                if (!this.form.account_name) {
                    uni.showToast({
                        title: '银行卡号必填',
                        icon: 'none'
                    });
                    return false;
                }
                if (!this.form.bank_id) {
                    uni.showToast({
                        title: '银行卡所属银行必填',
                        icon: 'none'
                    });
                    return false;
                }
                if (!this.form.account_name) {
                    uni.showToast({
                        title: '银行预留手机号必填',
                        icon: 'none'
                    });
                    return false;
                }
                this.request(API.addUserSettle, 'POST', this.form, true).then(res => {
                    if (res.code === 0) {
                        uni.showToast({
                            title: '新增成功',
                            icon: 'success'
                        });
                        setTimeout(() => {
                            this.close();
                            this.getUserSettle();
                        }, 2000)
                    } else {
                        uni.showToast({
                            title: res.msg,
                            icon: 'none'
                        });
                    }
                });
            },
            formatIdCard(id_card) {
                if (id_card.length > 7) {
                    return id_card.slice(0, 3) + '*'.repeat(id_card.length - 7) + id_card.slice(-4);
                }
                return id_card;
            },
            formatBankNumber(bank_number) {
                if (bank_number.length > 4) {
                    return ''.repeat(bank_number.length - 4) + bank_number.slice(-4);
                }
                return bank_number;
            }
        }
    };
</script>

<style scoped lang="scss">
    @import '@/assets/css/bank/withdraw.scss';
</style>